package com.ruoyi.electronicFence.service.impl;

import com.ruoyi.common.config.DbInterfaceConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.electronicFence.domain.vo.ReqVo;
import com.ruoyi.electronicFence.task.RegularlyModifyEnableStatusTasks;
import com.ruoyi.electronicFence.utils.HttpUtil;
import com.ruoyi.electronicFence.utils.IdUtils;
import com.ruoyi.electronicFence.domain.A2ROfEFIntrusion;
import com.ruoyi.electronicFence.domain.ElectronicFence;
import com.ruoyi.electronicFence.domain.RegionalInfo;
import com.ruoyi.electronicFence.service.ElectronicFenceService;
import com.ruoyi.electronicFence.service.RegionalInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【a2_electronic fence(电子围栏列表)】的数据库操作Service实现
* @createDate 2025-02-11 13:34:24
*/
@Service
@Slf4j
public class ElectronicFenceServiceImpl
    implements ElectronicFenceService{

    @Autowired
    private RegionalInfoService regionalInfoService;



    @Autowired
    private RegularlyModifyEnableStatusTasks regularlyModifyqyztTasks;

    @Override
    @Transactional
    public AjaxResult insertOne(ElectronicFence electronicFence) {
        //先保存区域
        // 选择其他区域作为电子围栏时，不需要添加区域， 直接保存
        if(StringUtils.isNull(electronicFence.getGlid())) {
            //设置区域范围
            RegionalInfo regionalInfo = new RegionalInfo();
            regionalInfo.setQymc(electronicFence.getQymc());
            regionalInfo.setQyjson(electronicFence.getQyjson());

            Long regionalId = regionalInfoService.addRegional(regionalInfo);
            electronicFence.setGlid(regionalId);
        }
        electronicFence.setSjcrsj(new Date());

//        int resultCount = electronicFenceMapper.insert(electronicFence);

        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO J_KY_R_DZWLLB ( id, sjcrsj");
        if(StringUtils.isNotNull(electronicFence.getGlid())){
            sb.append(",glid");
        }
        if(StringUtils.isNotNull(electronicFence.getKssj())){
            sb.append(" ,kssj");
        }
        if(StringUtils.isNotNull(electronicFence.getJssj())){
            sb.append(", jssj");
        }
        if(StringUtils.isNotNull(electronicFence.getQyzt())){
            sb.append(", qyzt");
        }
        sb.append(")VALUES ( ")
                .append(IdUtils.generateId())
                .append(" ,'" + DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));

        if(StringUtils.isNotNull(electronicFence.getGlid())){
            sb.append("' ," + electronicFence.getGlid());
        }
        if(StringUtils.isNotNull(electronicFence.getKssj())){
            sb.append(" ,'" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, electronicFence.getKssj()));
        }
        if(StringUtils.isNotNull(electronicFence.getJssj())){
            sb.append("' ,'" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, electronicFence.getJssj())).append("'");
        }
        if(StringUtils.isNotNull(electronicFence.getQyzt())){
            sb.append(" ," + electronicFence.getQyzt());
        }
        sb.append(")");

        HttpUtil.create(dbInterfaceConfig, new ReqVo(sb.toString()));


        //实现 设置开始结束时间后，自定关闭开启状态；
//        if (electronicFence.getQyzt() == 2 && StringUtils.isNotNull(electronicFence.getKssj()) && StringUtils.isNotNull(electronicFence.getJssj())) {
//            Date now = new Date();
//            //时间校验，避免因定时任务无法执行导致系统不能启动
//            if(now.before(electronicFence.getKssj())){
//                try {
//                    SysJob sysJob = new SysJob();
//                    sysJob.setJobName(ScheduleConstants.ELE_START_JOBNAME_lx + electronicFence.getRwid());
//                    sysJob.setJobGroup(ScheduleConstants.ELE_GROUP_NAME);
//                    sysJob.setInvokeTarget("UpdateqyztTask.run(" + electronicFence.getRwid() + "," + 1 + ")");
//                    sysJob.setCronExpression(CronUtils.convertDateToCron(electronicFence.getKssj()));
//                    sysJob.setMisfirePolicy(ScheduleConstants.MISFIRE_DEFAULT);
//                    sysJob.setConcurrent("0");
//                    sysJob.setStatus("0");
//                    iSysJobService.insertJob0212(sysJob);
//                } catch (Exception e) {
//                    log.error("保存开始时间定时任务失败", e);
//                    throw new ServiceException("保存开始时间定时任务失败");
//                }
//            }
//            if(now.before(electronicFence.getJssj())){
//                try {
//                    SysJob sysJob = new SysJob();
//                    sysJob.setJobName(ScheduleConstants.ELE_END_JOBNAME_lx + electronicFence.getRwid());
//                    sysJob.setJobGroup(ScheduleConstants.ELE_GROUP_NAME);
//                    sysJob.setInvokeTarget("UpdateqyztTask.run(" + electronicFence.getRwid() + "," + 2 + ")");
//                    sysJob.setCronExpression(CronUtils.convertDateToCron(electronicFence.getJssj()));
//                    sysJob.setMisfirePolicy(ScheduleConstants.MISFIRE_DEFAULT);
//                    sysJob.setConcurrent("0");
//                    sysJob.setStatus("0");
//                    iSysJobService.insertJob0212(sysJob);
//                } catch (Exception e) {
//                    log.error("保存结束时间定时任务失败", e);
//                    throw new ServiceException("保存结束时间定时任务失败");
//                }
//            }

//        }
        try{
            regularlyModifyqyztTasks.initEleSet();
        }catch (Exception e) {
            log.error("更新电子围栏失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult updateByrwidAndRegionalId(ElectronicFence electronicFence) {
//        RegionalInfo regionalInfo = new RegionalInfo();
//        regionalInfo.setQy_geojson(electronicFence.getQy_geojson());
//        regionalInfo.setqymc(electronicFence.getqymc());
//        regionalInfo.setId(electronicFence.getQyid());
//        regionalInfoService.updateById(regionalInfo);
        if(electronicFence.getQyzt() == 1 && StringUtils.isNotNull(electronicFence.getKssj()) && StringUtils.isNotNull(electronicFence.getJssj())){
            //todo   调用方法  到结束时间自动关闭
        }
//        electronicFenceMapper.updateById(electronicFence);

        StringBuilder sb = new StringBuilder();
        sb.append("UPDATE J_KY_R_DZWLLB SET ");
        if(StringUtils.isNotNull(electronicFence.getQyzt())){
            sb.append("qyzt = " + electronicFence.getQyzt()).append(",");
        }
        if(StringUtils.isNotNull(electronicFence.getKssj())){
            sb.append("kssj = '" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, electronicFence.getKssj()) +"'").append(",");
        }
        if(StringUtils.isNotNull(electronicFence.getJssj())){
            sb.append("jssj = '" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, electronicFence.getJssj()) +"'").append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append("where id = " + electronicFence.getId());
        HttpUtil.create(dbInterfaceConfig, new ReqVo(sb.toString()));
        try{
            regularlyModifyqyztTasks.initEleSet();
        }catch (Exception e) {
            log.error("更新电子围栏失败");
        }

        return AjaxResult.success();
    }

    @Autowired
    private DbInterfaceConfig dbInterfaceConfig;

    @Override
    public ElectronicFence selectEleById(Long id) {

        //todo sql
//        ElectronicFence electronicFence = electronicFenceMapper.selectById(id);
        StringBuilder sb1 = new StringBuilder("");
        sb1.append("SELECT * FROM J_KY_R_DZWLLB WHERE id=").append(id);
        ElectronicFence electronicFence = (ElectronicFence) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(sb1.toString()), ElectronicFence.class);


        //todo sql
//        QueryWrapper<RegionalInfo> regionWrapper = new QueryWrapper<>();
//        regionWrapper.select("id", "qy_geojson");
//        regionWrapper.eq("id", electronicFence.getQyid());
//        RegionalInfo regionalInfo = regionalInfoService.getOne(regionWrapper);

        StringBuilder sb2 = new StringBuilder("");
        sb2.append("SELECT id, qymc, qyjson FROM J_KY_S_QYXXB WHERE id = ").append(electronicFence.getGlid());
        RegionalInfo regionalInfo = (RegionalInfo) HttpUtil.getBean(dbInterfaceConfig, new ReqVo(sb2.toString()), RegionalInfo.class);

        electronicFence.setQyjson(regionalInfo.getQyjson());
        electronicFence.setQymc(regionalInfo.getQymc());
        return electronicFence;
    }

    @Override
    public List<ElectronicFence> listByPage(String regionalName, Integer qyzt) {
//        return electronicFenceMapper.listByPage(regionalName, qyzt);
        return null;
    }

    @Override
    public List<RegionalInfo> selectOtherList() {
        //todo sql
//        QueryWrapper<ElectronicFence> eleQueryWrap = new QueryWrapper<>();
//        eleQueryWrap.select("qyid");
//        List<ElectronicFence> electronicFences = electronicFenceMapper.selectList(eleQueryWrap);
//        List<Long> collect = electronicFences.stream().map(ele -> ele.getQyid()).collect(Collectors.toList());
        StringBuilder sb = new StringBuilder("SELECT glid FROM J_KY_R_DZWLLB");
        List<ElectronicFence> electronicFences = (List<ElectronicFence>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb.toString()), ElectronicFence.class);
        List<Long> collect = electronicFences.stream().map(ele -> ele.getGlid()).collect(Collectors.toList());
//        QueryWrapper<RegionalInfo> regionWrapper = new QueryWrapper<>();
//        regionWrapper.select("id", "qymc")
//                .notIn(CollectionUtil.isNotEmpty(collect), "id", collect);
//        List<RegionalInfo> list = regionalInfoService.list(regionWrapper);
        StringBuilder sb1 = new StringBuilder();
        sb1.append("SELECT id,qymc FROM J_KY_S_QYXXB WHERE id NOT IN (");
        collect.forEach(qyid -> {
            sb1.append(qyid + ",");
        });
        sb1.deleteCharAt(sb1.length() - 1).append(")");
        List<RegionalInfo> listBean = (List<RegionalInfo>) HttpUtil.getListBean(dbInterfaceConfig, new ReqVo(sb1.toString()), RegionalInfo.class);
        return listBean;
    }

    @Override
    public AjaxResult updateqyztById(Long id, Integer qyzt) {
//        UpdateWrapper<ElectronicFence> electronicFenceQueryWrapper = new UpdateWrapper<>();
//        electronicFenceQueryWrapper.eq("rwid", id);
//        electronicFenceQueryWrapper.set("qyzt", qyzt);

        StringBuilder sb  = new StringBuilder("UPDATE J_KY_R_DZWLLB SET qyzt = ");
        sb.append(qyzt +  " where id = " +  id);
        HttpUtil.create(dbInterfaceConfig, new ReqVo(sb.toString()));
        return AjaxResult.success();
    }

    @Override
    public AjaxResult batchUpdateqyzt(List<Long> idList, Integer qyzt) {
        try {
//            UpdateWrapper<ElectronicFence> wrapper = new UpdateWrapper<>();
//            wrapper.in("rwid", idList);
//            wrapper.set("qyzt", qyzt);
////            wrapper.set("kssj", null);
////            wrapper.set("jssj", null);
//            electronicFenceMapper.update(null, wrapper);

            //todo sql
            StringBuilder sb = new StringBuilder("UPDATE J_KY_R_DZWLLB SET qyzt=");
            sb.append(qyzt + " where id in (");
            idList.forEach(id -> {
                sb.append(id + ",");
            });
            sb.deleteCharAt(sb.length() - 1).append(")");
            HttpUtil.create(dbInterfaceConfig, new ReqVo(sb.toString()));

            return AjaxResult.success();
        } catch (Exception e) {
            log.error("修改失败",  e);
            return AjaxResult.error();
        }
    }

    @Override
    public List<ElectronicFence> isBreakOrOut(BigDecimal lon, BigDecimal lat, Date baseTime) {
//        return electronicFenceMapper.isContain(lon, lat, baseTime);
        return null;
    }

    @Override
    public List<A2ROfEFIntrusion> selectjczt(Long rwid, Integer jczt, String targetName) {
//        return electronicFenceMapper.selectjczt(rwid, jczt, targetName);
        return null;
    }


    /**
     * @description:  添加电子围栏 start  end  状态定时任务
     * @author: wsl
     * @date: 2025-02-12 15:10
     * @param: electronicFence
     * @param: qyzt
     * @return: java.lang.Integer
     **/
//    public Integer saveSysJob(ElectronicFence electronicFence, Integer qyzt){
//        SysJob sysJob = new SysJob();
//        sysJob.setJobName(ScheduleConstants.ELE_START_JOBNAME_lx + electronicFence.getRwid());
//        sysJob.setJobGroup("ele");
//        sysJob.setInvokeTarget("myTask.run()");
//        sysJob.setCronExpression(CronUtils.convertDateToCron(electronicFence.getKssj()));
//        sysJob.setMisfirePolicy(ScheduleConstants.MISFIRE_DEFAULT);
//        sysJob.setConcurrent("0");
//        sysJob.setStatus("0");
//        try {
//            return iSysJobService.insertJob0212(sysJob);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
}




